﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Xml;
using CNVP.Config;
using CNVP.Framework.Helper;
using System.Threading;

namespace CNVP.Framework.Utils
{
    public class Public
    {
        #region "获取用户IP地址"
        /// <summary>
        /// 获取用户IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserIP()
        {
            string _UserIP = "";
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                _UserIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                _UserIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return _UserIP;
        }
        #endregion
        #region "获取网站访问地址"
        /// <summary>
        /// 获取网站访问地址
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            Uri _Uri = HttpContext.Current.Request.Url;
            if (_Uri.Port.ToString() == "80")
            {
                return _Uri.Host.ToLower();
            }
            else
            {
                return _Uri.Host.ToLower() + ":" + _Uri.Port.ToString();
            }
        }
        #endregion
        #region "获取远程文件"
        /// <summary>
        /// 获取远程文件
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetRemoteValue(string Url)
        {
            try
            {
                WebRequest request = WebRequest.Create(Url);
                WebResponse response = request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);

                string strHtmlText = sr.ReadToEnd();
                resStream.Dispose();
                sr.Dispose();
                return strHtmlText;
            }
            catch (Exception ex)
            {
                LogHelper.Write("下载文件失败", ex.ToString()); 
                return "";
            }
        }
        #endregion
        #region "模块安装、升级"
        #region "获取远程模块信息"
        public static DataTable GetRemoteAllModule()
        {
            try
            {
                XmlDocument Xml = new XmlDocument();
                Xml.Load("http://JCms.Cnvp.Com.Cn/API/GetModule.ashx");
                XmlNodeList RootList = Xml.SelectNodes("module/item");

                DataTable _Dt = new DataTable("Result");
                _Dt.Columns.Add("ModuleKey", typeof(string));
                _Dt.Columns.Add("ModuleName", typeof(string));
                _Dt.Columns.Add("ModuleVersion", typeof(string));
                _Dt.Columns.Add("PostTime", typeof(string));

                foreach (XmlNode Xn in RootList)
                {
                    DataRow _Rows = _Dt.NewRow();
                    _Rows["ModuleKey"] = Xn.Attributes["modulekey"].InnerText;
                    _Rows["ModuleName"] = Xn.Attributes["modulename"].InnerText;
                    _Rows["ModuleVersion"] = Xn.Attributes["moduleversion"].InnerText;
                    _Rows["PostTime"] = Xn.Attributes["posttime"].InnerText;
                    _Dt.Rows.Add(_Rows);
                }
                return _Dt;
            }
            catch (Exception ex)
            {
                LogHelper.Write("模块获取失败", ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取远程模块版本及安装文件地址
        /// </summary>
        /// <param name="ModuleKey"></param>
        /// <returns></returns>
        public static DataTable GetRemoteModuleInfo(string ModuleKey)
        {
            try
            {
                XmlDocument Xml = new XmlDocument();
                Xml.Load(string.Format("http://JCms.Cnvp.Com.Cn/API/GetModule.ashx?Action=GetModuleInfo&ModuleKey={0}", ModuleKey));
                XmlNodeList RootList = Xml.SelectNodes("module/item");

                DataTable _Dt = new DataTable("Result");
                _Dt.Columns.Add("ModuleKey", typeof(string));
                _Dt.Columns.Add("ModuleName", typeof(string));
                _Dt.Columns.Add("ModuleVersion", typeof(string));
                _Dt.Columns.Add("ModuleUrl", typeof(string));
                _Dt.Columns.Add("PostTime", typeof(string));

                foreach (XmlNode Xn in RootList)
                {
                    DataRow _Rows = _Dt.NewRow();
                    _Rows["ModuleKey"] = Xn.Attributes["modulekey"].InnerText;
                    _Rows["ModuleName"] = Xn.Attributes["modulename"].InnerText;
                    _Rows["ModuleVersion"] = Xn.Attributes["moduleversion"].InnerText;
                    _Rows["ModuleUrl"] = string.Format("http://JCms.Cnvp.Com.Cn/Module/{0}", Xn.Attributes["moduleurl"].InnerText);
                    _Rows["PostTime"] = Xn.Attributes["posttime"].InnerText;
                    _Dt.Rows.Add(_Rows);
                }
                return _Dt;
            }
            catch (Exception ex)
            {
                LogHelper.Write("获取远程模块版本及安装文件地址失败", ex.ToString());
                return null;
            }
        }
        #endregion
        /// <summary>
        /// 远程下载文件
        /// </summary>
        /// <param name="sURL"></param>
        /// <param name="Filename"></param>
        /// <param name="msg"></param>
        public static void DownloadFile(string sURL, string Filename, string msg)
        {
            System.Net.HttpWebRequest URLReq;
            System.Net.HttpWebResponse URLRes;
            System.IO.FileStream FileStreamer;
            int iBytesRead = 0;
            long num = 0;
            try
            {
                FileStreamer = new System.IO.FileStream(Filename, System.IO.FileMode.Create);
                URLReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sURL);
                URLRes = (System.Net.HttpWebResponse)URLReq.GetResponse();
                System.IO.Stream sChunks = URLReq.GetResponse().GetResponseStream();
                long a = URLRes.ContentLength;
                byte[] bBuffer = new byte[a + 100];
                string jsBlock = string.Empty;
                do
                {
                    iBytesRead = sChunks.Read(bBuffer, 0, (int)a + 100);
                    FileStreamer.Write(bBuffer, 0, iBytesRead);
                    num += iBytesRead;
                    int i = Convert.ToInt32(((double)num / (double)a) * 100);
                    jsBlock = "<script" + ">SetPorgressBar('" + msg + "','" + i.ToString() + "');<" + "/script>";
                    HttpContext.Current.Response.Write(jsBlock);
                    HttpContext.Current.Response.Flush();
                }
                while (iBytesRead != 0);
                sChunks.Close();
                FileStreamer.Close();
            }
            catch (Exception e)
            {
                Helper.LogHelper.Write("文件下载失败", e.ToString());
            }
        }
        /// <summary>
        /// 重写HTML代码(实现进度条功能)
        /// </summary>
        /// <returns></returns>
        public static void RewriteHTML()
        {
string Str = @"<html xmlns=""http://www.w3.org/1999/xhtml"">
<head runat=""server"">
<title></title>
</head>
<script" + @" language=""javascript"">
//开始处理
function BeginTrans(msg) {
WriteText(""Msg1"", msg);
}
//设置进度条进度
function SetPorgressBar(msg, pos) {
ProgressBar.style.width = pos + ""%"";
WriteText(""Msg1"", msg + "" 已完成"" + pos + ""%"");
}
//处理结束
function EndTrans(msg) {
if (msg == """")
WriteText(""Msg1"", ""完成。"");
else
WriteText(""Msg1"", msg);
}
//设置时间信息
function SetTimeInfo(msg) {
WriteText(""Msg2"", msg);
}
// 更新文本显示信息
function WriteText(id, str) {
var strTag = '<font face=""Verdana, Arial, Helvetica"" size=""2"" color=""#ea9b02""><B>' + str + '</B></font>';
if (document.all) document.all[id].innerHTML = strTag;
}
<" + @"/script>
<body>
<table align=""center"" style=""height:100%;"" id=""main"">
<tr style=""height:45%""><td></td></tr>
<tr>
<td>
<div id=""Msg1"" style=""height:16px;""><font face=""Verdana, Arial, Helvetica"" size=""2"" color=""#ea9b02""><b>正在加载...</b></font></div>
<div id=""ProgressBarSide"" style=""width:380px; color:Silver;border-width:1px; border-style:Solid;"">
<div id=""ProgressBar"" align=""center"" style=""height:20px; width:0%; background-color:#316AC5;""></div>
</div>
<div id=""Msg2"" style=""height:16px;""><font face=""Verdana, Arial, Helvetica"" size=""2"" color=""#ea9b02""><b></b></font></div>
</td>
</tr>
<tr style=""height:50%""><td></td></tr>
</table>
</body>
</html>";
           HttpContext.Current.Response.Write(Str);
           HttpContext.Current.Response.Flush();
        }
        /// <summary>
        /// 单步系统数据库更新程序
        /// </summary>
        public static void DataUpdate(string LocalFolder)
        {
            string jsBlock;
            #region "更新表的操作"
            string Setup1 = LocalFolder + "/sql.txt";
            if (FileUtils.FileExists(Setup1))
            {
                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('正在执行数据表更新操作...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();

                StringBuilder sb = new StringBuilder();
                using (StreamReader objReader = new StreamReader(Setup1, Encoding.UTF8))
                {
                    sb.Append(objReader.ReadToEnd());
                    objReader.Close();
                    DbHelper.ExecuteCommandWithSplitter(sb.ToString().Replace("CNVP_", DBConfig.Prefix));
                }
                FileUtils.DeleteFile(Setup1);

                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('数据表更新成功...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();
            }
            Thread.Sleep(500);
            #endregion
        }
        /// <summary>
        /// 执行更新程序
        /// </summary>
        public static void ModuleUpdate(string LocalFolder)
        {
            string jsBlock;
            #region "删除表的操作"
            string Setup1 = LocalFolder + "/Setup1.Sql";
            if (FileUtils.FileExists(Setup1))
            {
                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('正在执行删除表的操作...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();

                StringBuilder sb = new StringBuilder();
                using (StreamReader objReader = new StreamReader(Setup1, Encoding.UTF8))
                {
                    sb.Append(objReader.ReadToEnd());
                    objReader.Close();
                    DbHelper.ExecuteNonQuery(sb.ToString().Replace("CNVP_", DBConfig.Prefix));
                }
                FileUtils.DeleteFile(Setup1);

                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('删除表操作成功...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();
            }
            Thread.Sleep(500);
            #endregion
            #region "创建表的操作"
            string Setup2 = LocalFolder + "/Setup2.Sql";
            if (FileUtils.FileExists(Setup2))
            {
                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('正在执行创建表的操作...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();

                StringBuilder sb = new StringBuilder();
                using (StreamReader objReader = new StreamReader(Setup2, Encoding.UTF8))
                {
                    sb.Append(objReader.ReadToEnd());
                    objReader.Close();
                    DbHelper.ExecuteCommandWithSplitter(sb.ToString().Replace("CNVP_", DBConfig.Prefix));
                }
                FileUtils.DeleteFile(Setup2);

                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('创建表操作成功...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();
            }
            Thread.Sleep(500);
            #endregion
            #region "初始化数据的操作"
            string Setup3 = LocalFolder + "/Setup3.Sql";
            if (FileUtils.FileExists(Setup3))
            {
                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('正在数据初始化操作...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();

                StringBuilder sb = new StringBuilder();
                using (StreamReader objReader = new StreamReader(Setup3, Encoding.UTF8))
                {
                    sb.Append(objReader.ReadToEnd());
                    objReader.Close();
                    DbHelper.ExecuteNonQuery(sb.ToString().Replace("CNVP_", DBConfig.Prefix));
                }
                FileUtils.DeleteFile(Setup3);

                Thread.Sleep(500);
                jsBlock = "<script" + ">BeginTrans('数据初始化操作成功...');<" + "/script>";
                HttpContext.Current.Response.Write(jsBlock);
                HttpContext.Current.Response.Flush();
            }
            Thread.Sleep(500);
            #endregion
        }
        #endregion
        #region "远程下载授权码"
        /// <summary>
        /// 远程下载授权码
        /// </summary>
        /// <param name="License"></param>
        /// <returns></returns>
        public static void GetLicense(string Str,out bool flg)
        {
            flg = false;
            try
            {
                XmlDocument XmlDoc = new XmlDocument();
                string _Url = string.Format("http://Jcms.Cnvp.Com.Cn/API/GetLicense.ashx?License={0}", Str);
                XmlDoc.Load(_Url);
                XmlNodeList NodeList = XmlDoc.GetElementsByTagName("SiteConfig");
                string _License = NodeList.Item(0)["License"].InnerText.ToString();
                string _ExpireTime = NodeList.Item(0)["ExpireTime"].InnerText.ToString();
                string _Domains = NodeList.Item(0)["Domains"].InnerText.ToString();
                string _PostTime = NodeList.Item(0)["PostTime"].InnerText.ToString();

                //保存配置文件
                BaseConfig.SaveXmlConfig("License", _License);
                BaseConfig.SaveXmlConfig("ExpireTime", _ExpireTime);
                BaseConfig.SaveXmlConfig("Domains", _Domains);
                BaseConfig.SaveXmlConfig("PostTime", _PostTime);

                //刷新缓存文件
                LicenseConfig.RefurbishCatch();
                flg = true;
            }
            catch(Exception ex)
            {
                LogHelper.Write("授权码下载失败", ex.ToString());
            }
        }
        #endregion
        #region "检查是否为授权文件"
        /// <summary>
        /// 输出错误信息
        /// </summary>
        /// <returns></returns>
        public static string ErrorHTML()
        {
            StringBuilder Str=new StringBuilder();
            Str.Append("<html>");
            Str.Append("<head>");
            Str.Append("<title>错误信息</title>");
            Str.Append("<style type=\"text/css\">");
            Str.Append("body{font-size:13px;margin:0px;padding:0px}");
            Str.Append("table,td{font-size:13px;margin:0px;padding:0px}");
            Str.Append("</style>");
            Str.Append("</head>");
            Str.Append("<body>");
            Str.Append("<table width=\"450\" height=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">");
            Str.Append("<tr>");
            Str.Append("<td>");
            Str.Append("<table width=\"450\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"background:#FFC;border:solid 1px #CCCCCC\">");
            Str.Append("<tr>");
            Str.Append("<td height=\"50\">");
            Str.Append("<table width=\"420\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">");
            Str.Append("<tr>");
            Str.Append("<td height=\"35\">警告：该页面未经系统授权被拒绝访问，请登录后台重建文件比对操作！</td>");
            Str.Append("</tr>");
            Str.Append("</table></td>");
            Str.Append("</tr>");
            Str.Append("</table></td>");
            Str.Append("</tr>");
            Str.Append("</table>");
            Str.Append("</body>");
            Str.Append("</html>");
            return Str.ToString();
        }
        #endregion
        #region "过滤特殊符号"
        /// <summary>
        /// 过滤特殊特号(完全过滤)
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string FilterSql(string Str)
        {
            string[] aryReg = { "'", "\"", "\r", "\n", "<", ">", "%", "?", ",", "=", "-", "_", ";", "|", "[", "]", "&", "/" };
            if (!string.IsNullOrEmpty(Str))
            {
                foreach (string str in aryReg)
                {
                    Str = Str.Replace(str, string.Empty);
                }
                return Str;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 过滤特殊符号(简单过滤)
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string FilterSql1(string Str)
        {
            string[] aryReg = { "'", ";", "\"", "\r", "\n", "<", ">" };
            foreach (string str in aryReg)
            {
                Str = Str.Replace(str, string.Empty);
            }
            return Str;
        }
        /// <summary>
        /// 过滤特殊符号(简单过滤)
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string FilterSqlString(string Str)
        {
            Str = Regex.Replace(Str,@";|\\|\r|\n|<|>|--|\[|\]|go|update|insert","",RegexOptions.IgnoreCase);
            return Str;
        }
        /// <summary>
        /// 过滤特殊符号(样式管理)
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string FilterStr(string Str)
        {
            if (!string.IsNullOrEmpty(Str))
            {
                Str = Str.Replace("\"", "'");
                Str = Str.Replace("\r", "");
                Str = Str.Replace("\n", "");
            }
            return Str;
        }
        /// <summary>
        /// 过滤HTML代码
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string FilterHTML(string Str)
        {
            if (!string.IsNullOrEmpty(Str))
            {
                string Pattern = @"<\/*[^<>]*>";
                return Regex.Replace(Str, Pattern, "");
            }
            else
            {
                return "";
            }
        }
        #endregion
        #region "参数格式检查"
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber(string inputData)
        {
            return Regex.IsMatch(inputData, @"^(\d)+$", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 判断是否为数字集合
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumericSet(string inputData)
        {
            return Regex.IsMatch(inputData, @"^((\d)+(,)?)+$", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 是否是邮件地址
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            return Regex.IsMatch(inputData, @"^[\w-]+@[\w-]+\.(com|cc|hk|la|cn|net|org|edu|mil|tv|biz|info)$", RegexOptions.IgnoreCase);
        }
        #endregion
        #region "DataTable转换成JSON"
        /// <summary>
        /// DataTable转换成JSON
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DtToJSON(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName.ToString());
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }
        #endregion
        #region "比较两个字符串相似度"
        /// <summary>
        /// 比较两个字符串相似度
        /// </summary>
        /// <param name="fromString">原始值</param>
        /// <param name="toString">比较值</param>
        /// <returns>差异值，返回0表示一致</returns>
        public static int CompareStrings(string fromString, string toString)
        {
            var fLength = fromString.Length;
            var tLength = toString.Length;

            if (fLength == 0)
            {
                return tLength;
            }
            if (tLength == 0)
            {
                return fLength;
            }
            var martix = new int[fLength + 1, tLength + 1];
            for (int i = 0; i <= fLength; i++)
            {
                martix[i, 0] = i;
            }

            for (int j = 0; j <= tLength; j++)
            {
                martix[0, j] = j;
            }
            for (int i = 1; i <= fLength; i++)
            {
                var tempF = fromString[i - 1];
                var cost = 0;
                for (int j = 1; j <= tLength; j++)
                {
                    var tempT = toString[j - 1];
                    if (tempT == tempF)
                    {
                        cost = 0;
                    }
                    else
                    {
                        cost = 1;
                    }

                    var valueAbove = martix[i - 1, j] + 1;
                    var valueLeft = martix[i, j - 1] + 1;
                    var valueDiag = martix[i - 1, j - 1] + cost;

                    var cellValue = valueAbove < valueLeft ? (valueDiag < valueAbove ? valueDiag : valueAbove) : (valueDiag < valueLeft ? valueDiag : valueLeft);
                    martix[i, j] = cellValue;
                }
            }

            var result = martix[fLength, tLength];

            return result;
        }
        #endregion
        #region "获取安装路径字符串"
        public static string GetInstallDir(string Str)
        {
            if (string.IsNullOrEmpty(Str))
            {
                return null;
            }
            int _Length = UIConfig.InstallDir.Length;
            if (Str.Substring(0, _Length) == UIConfig.InstallDir)
            {
                Str = "{#InstallDir}"+Str.Remove(0, _Length);
            }
            return Str;
        }
        #endregion
        #region "判断操作权限"
        /// <summary>
        /// 权限校验测试
        /// </summary>
        /// <param name="AllPopedom"></param>
        /// <param name="Popedom"></param>
        /// <returns></returns>
        public static bool CheckPopedom(int AllPopedom,int Popedom)
        {
            bool flg = false;
            if (AllPopedom == Popedom)
            {
                flg = true;
            }
            else
            {
                flg=((AllPopedom & Popedom) == Popedom);
            }
            return flg;
        }
        #endregion
        #region 生成一段路径和文件名, 路径跟日期有关, 文件名跟时间有关.
        /// <summary>
        /// 生成一段路径和文件名, 路径跟日期有关, 文件名跟时间有关.
        /// </summary>
        /// <returns>数字字符串,没有后缀</returns>
        static public string getRandomFilename(string root)
        {
            System.Random rand = new System.Random();
            DateTime now = DateTime.Now;
            string path = "";
            path += now.Year.ToString() + "\\";
            path += now.Month.ToString() + "\\";
            path += now.Day.ToString() + "\\";
            if (!Directory.Exists(root + "\\" + path))
            {
                Directory.CreateDirectory(root + "\\" + path);
            }
            path += now.Hour.ToString();
            path += now.Minute.ToString();
            path += now.Second.ToString();
            path += rand.Next(0, 1000);
            return path.Replace("\\", "/");
        }
        #endregion
        #region 处理文件名
        /// <summary>
        /// 处理文件名
        /// </summary>
        /// <param name="argFn">路径及文件名</param>
        /// <param name="argSFn">待插入的子串</param>
        /// <returns>操作结果</returns>
        static public string parseFn(string argFn, string argSFn)
        {
            try
            {
                string postfix = argFn.Substring(argFn.LastIndexOf("."));
                return argFn.Substring(0, argFn.LastIndexOf(".")) + argSFn + postfix;
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return "";
        }
        #endregion
        #region 生成缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        #endregion
        #region 压缩Html文件
        /// <summary>
        /// 压缩Html文件
        /// </summary>
        /// <param name="html">Html文件</param>
        /// <returns></returns>
        public static string GZipHtml(string Html)
        {

            Html = Regex.Replace(Html, @">\s+?<", "><");//去除Html中的空白字符.
            Html = Regex.Replace(Html, @"\r\n\s*", "");
            Html = Regex.Replace(Html, @"<body([\s|\S]*?)>([\s|\S]*?)</body>", @"<body$1>$2</body>", RegexOptions.IgnoreCase);
            return Html;
        }
        #endregion
        #region 获取"|"第一个
        public static string GetFirst(string img)
        {
            string[] arrayStr = img.Split('|');
            try
            {
                return arrayStr[0];
            }
            catch
            {
                return "Images/err_img.jpg";
            }
        }
        #endregion
        #region 获取"|"第二个
        public static string GetSecond(string img)
        {
            string[] arrayStr = img.Split('|');
            try
            {
                return arrayStr[1];
            }
            catch
            {
                return "Images/err_img.jpg";
            }
        }
        #endregion


        #region 获取当前时间戳
        public static long GetTimeStamp()
        {
            try
            {
                DateTime startime = new DateTime(1970, 1, 1);
                long timestamp = (DateTime.Now.Ticks - startime.Ticks) / 1000000;
                return timestamp;
            }
            catch
            {
                return 0;
            }
        }
        #endregion
        #region 时间戳转换成日期
        public static DateTime StampToDate(long nowdate)
        {

            DateTime dtStart = new DateTime(1970, 1, 1);
            long strlong = (nowdate * 1000000) + dtStart.Ticks;
            try
            {

                return dtStart = new DateTime(strlong);
            }
            catch
            {
                return DateTime.Now;
            }
        }
        #endregion
        #region 日期转成时间戳
        public static long DateToStamp(DateTime dt)
        {
            try
            {
                DateTime startime = new DateTime(1970, 1, 1);
                long timestamp = (dt.Ticks - startime.Ticks) / 1000000;
                return timestamp;
            }
            catch
            {
                return 0;
            }
        }
        #endregion
        #region 计算二个时间差是否为一天人会天数
        public static int DateSubDate(DateTime dt, DateTime dt2)
        {
            try
            {
                long stamp1 = DateToStamp(dt.Date);
                long stamp2 = DateToStamp(dt2.Date);
                long dtd = stamp1 - stamp2;
                long daysecond = 3600 * 24;
                long count = 0;
                if (stamp1 > stamp2)
                {
                    count = stamp1 - stamp2;
                }
                else
                {

                    count = stamp2 - stamp1;

                }
                return int.Parse((count / daysecond).ToString());

            }
            catch
            {
                return -1;
            }
        }
        #endregion
        #region 计算二个时间差是否为一天人会天数
        public static long AddDate(DateTime dt, int num)
        {
            try
            {
                long stamp1 = DateToStamp(dt.Date);

                long daysecond = 3600 * 24 * num;

                return stamp1 + daysecond;

            }
            catch
            {
                return -1;
            }
        }
        #endregion
    }
}